# !/usr/bin/env python
# _*_ coding:utf-8 _*_

import time
import datetime
import os
import conf
import smtplib
from email.mime.text import MIMEText


class Day(object):
    @staticmethod
    def any_day(add_days):
        today = datetime.date.today()
        utl_add_day = str(today - datetime.timedelta(days=int(add_days)))
        return utl_add_day


class MysqlBackup(object):
    def __init__(self, **kargs):
        self.__host = kargs['host']
        self.__dbname = kargs['db']
        self.__username = kargs['user']
        self.__password = kargs['passwd']
        self.__port = kargs['port']

    def BakData(self, backup_file):
        cmd_bak = 'mysqldump -u ' + self.__username + ' -p' + self.__password + ' -h' + self.__host + ' ' + self.__dbname + ' --single-transaction ' + ' > ' + backup_file
        outp = os.system(cmd_bak)
        return cmd_bak, outp

    def TarData(self, date):
        cmd_tar = 'tar zcf ' + conf.backup_path + self.__dbname + '_' + date + '.zip ' + '-C ' + conf.backup_path + self.__dbname + '_' + date + '.dump >> /dev/null 2>&1'
        outp = os.system(cmd_tar)
        return cmd_tar, outp

    @property
    def dbname(self):
        return self.__dbname


def main():
    DATA_DATE = Day.any_day(1)

    DB_BAK_INFO = MysqlBackup(**conf.conn_dict)
    backup_file = conf.backup_path + DB_BAK_INFO.dbname + '_' + DATA_DATE + '.dump'
    print backup_file
    log_file = conf.backup_path + DB_BAK_INFO.dbname + '.log'

    with open(log_file, 'a') as f:
        f.write('\n\n ***********************\n')
        f.write(' * ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' *\n')
        f.write(' ***********************\n')

        if os.path.isfile(backup_file) is False:

            cmd_result = DB_BAK_INFO.BakData(backup_file)
            print cmd_result
            f.write('** COMMAND     :' + cmd_result[0] + '\n')
            f.write('** DATABASE    : ' + DB_BAK_INFO.dbname + '\n')
            f.write('** DATA_DATE   : ' + DATA_DATE + '\n')
            f.write('** RESULT(BAK) : ' + ('succeed\n' if cmd_result[1] == 0 else 'failed\n'))

            if cmd_result[1] == 0:
                tar_result = DB_BAK_INFO.TarData(DATA_DATE)
                f.write('** COMMAND     :' + tar_result[0] + '\n')
                f.write('** RESULT(TAR) : ' + ('succeed' if tar_result[1] == 0 else 'failed'))

        else:
            f.write('** RESULT(BAK) : ' + '%s is already exists\n' % backup_file)


if __name__ == '__main__':
    main()
